package com.lagou.edu.mvcframework;

import com.sun.org.slf4j.internal.Logger;
import com.sun.org.slf4j.internal.LoggerFactory;
import org.apache.catalina.Context;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.startup.Tomcat;

import java.io.File;

public class MySpringApplication {

    private Logger logger = LoggerFactory.getLogger(getClass());

    public static void run(Class<?> aClass) throws LifecycleException {
        long start = System.currentTimeMillis();
        // 设置端口
        int port = 8080;
        Tomcat tomcat = new Tomcat();
        tomcat.setPort(port);

        // 设置contextPath和路径
        String contextPath = "";
        File file = new File("webapp");
        if(!file.exists()){
            file.mkdirs();
        }
        String docBase = file.getAbsolutePath();

        Context context = tomcat.addWebapp(contextPath, docBase);
        System.out.println("添加contextPath和docBase是:" + contextPath + "==>" + docBase);

        // add servlet
        String servletName = "Lgservlet";
        String servletMapping = "/*";
        tomcat.addServlet(contextPath, servletName, new LgDispatcherServices(aClass.getPackage().getName()));
        context.addServletMappingDecoded(servletMapping, servletName);
        // 启动tomcat
        tomcat.start();
        long end = System.currentTimeMillis();
        System.out.println("启动完成,共使用了:" + (end - start) + "ms");
        // 进入监听状态,如果不进入监听状态,启动tomat后就会关闭tomcat
        tomcat.getServer().await();
    }

}
